const path = require("path");

const {
  createUser,
  getUserInfo,
  updateById,
  findUsers,
  deleteUser,
  findAUser,
  updateUser,
} = require("../../services/admin/user.service");

const {
  userDoesNotExist,
  unSupportedFileType,
  invalidUserID,
} = require("../../constant/err.type");
const { JWT_SECRET } = require("../../config/config.default");

const jwt = require("jsonwebtoken");

class UserController {
  async register(ctx) {
    //1.获取数据
    // console.log(ctx.request.body);
    const { user_name, password, gender, avatar, introduction, is_admin } =
      ctx.request.body;

    //2. 操作数据库
    try {
      const res = await createUser(
        user_name,
        password,
        gender,
        avatar,
        introduction,
        is_admin
      );
      //3.返回结果
      ctx.body = {
        code: 0,
        message: "用户注册成功",
        result: {
          id: res.id,
          user_name: res.user_name,
          gender: res.gender,
        },
      };
    } catch (err) {
      console.log(err);
      //   ctx.app.emit("error", userRegisterError, ctx);
      return;
    }
  }

  async addUser(ctx) {
    //files后边跟.文件名
    // console.log(ctx.request.files.file);

    try {
      //拿到修改的数据
      const { gender, user_name, introduction, is_admin, password } =
        ctx.request.body;

      let avatar = "";
      const { file } = ctx.request.files;
      const fileTypes = ["image/jpeg", "image/png"];
      if (file) {
        if (!fileTypes.includes(file.mimetype)) {
          return ctx.app.emit("error", unSupportedFileType, ctx);
        }
        //public 作为静态资源目录 直接用其相对位置
        avatar = `/avataruploads/${path.basename(file.filepath)}`;
      }

      const res = await createUser({
        gender,
        user_name,
        introduction,
        avatar,
        password,
        is_admin,
      });
      if (res && avatar) {
        ctx.body = {
          code: 0,
          message: "添加用户成功",
        };
      } else {
        //如果没有头像传到后端，就不返回头像
        ctx.body = {
          code: 0,
          message: "添加用户失败",
        };
      }
    } catch (error) {
      console.error("添加用户出错:", error);
      ctx.body = {
        code: 1,
        message: "添加用户出错",
      };
    }
  }

  async login(ctx) {
    const { user_name } = ctx.request.body;

    //1.获取用户信息(在token的payload中，记录id,user_name,is_admin)
    try {
      //从返回结果对象中剔除password属性，将剩下的属性放到res对象
      const { password, ...res } = await getUserInfo({ user_name });

      const token = jwt.sign(
        { _id: res.id, user_name: res.user_name, is_admin: res.is_admin },
        JWT_SECRET,
        { expiresIn: "1d" }
      );
      ctx.set("Authorization", token);
      // res.avatar =
      //   "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png";
      ctx.body = {
        code: 0,
        message: "用户登录成功",
        result: {
          data: res,
        },
      };
    } catch (error) {
      console.error("用户登录失败", error);
      return ctx.app.emit("error", userDoesNotExist, ctx);
    }
  }
  async changePassword(ctx) {
    //1.获取数据
    const id = ctx.state.user.id;
    const password = ctx.request.body.password;
    // console.log(id, password);
    //2.操作数据库
    if (await updateById({ id, password })) {
      ctx.body = {
        code: 0,
        message: "修改密码成功",
        result: "",
      };
    } else {
      ctx.body = {
        code: "10007",
        message: "修改密码失败",
        result: "",
      };
    }
    //3.返回结果
  }

  //头像上传
  async upload(ctx) {
    //files后边跟.文件名
    // console.log(ctx.request.files.file);

    try {
      //拿到要修改数据的id
      const { authorization = "" } = ctx.request.header;
      const token = authorization.replace("Bearer ", "");
      const user = jwt.verify(token, JWT_SECRET);

      //拿到修改的数据
      const { gender, user_name, introduction } = ctx.request.body;
      let avatar = "";
      const { file } = ctx.request.files;
      const fileTypes = ["image/jpeg", "image/png"];
      if (file) {
        if (!fileTypes.includes(file.mimetype)) {
          return ctx.app.emit("error", unSupportedFileType, ctx);
        }
        //public 作为静态资源目录 直接用其相对位置
        avatar = `/avataruploads/${path.basename(file.filepath)}`;
      }
      const res = await updateById({
        id: user._id,
        gender,
        user_name,
        introduction,
        avatar,
      });
      if (res && avatar) {
        ctx.body = {
          code: 0,
          message: "修改信息成功",
          result: {
            // goods_img: path.basename(file.filepath), //拿到文件名
            user_name,
            gender,
            introduction,
            avatar, //拿到文件名
          },
        };
      } else {
        //如果没有头像传到后端，就不返回头像
        ctx.body = {
          code: 0,
          message: "修改信息失败",
          result: {
            // goods_img: path.basename(file.filepath), //拿到文件名
            user_name,
            gender,
            introduction,
          },
        };
      }
    } catch (error) {
      console.error("用户信息修改中出现错误:", error);
      ctx.body = {
        code: 1,
        message: "用户信息修改错误",
      };
    }
  }

  async findAll(ctx) {
    //1.解析pageNum和pageSize
    const { pageNum = 1, pageSize = 10 } = ctx.request.query;
    //2.调用数据处理的相关方法
    const res = await findUsers(pageNum, pageSize);
    //3.返回结果
    ctx.body = {
      code: 0,
      message: "获取用户列表成功",
      result: res,
    };
  }

  async remove(ctx) {
    try {
      const res = await deleteUser(ctx.params.id);

      if (res) {
        ctx.body = {
          code: 0,
          message: "删除用户成功成功",
          result: "",
        };
      } else {
        ctx.app.emit("error", invalidUserID, ctx);
      }
    } catch (error) {
      console.error(error);
    }
  }

  async findOne(ctx) {
    try {
      const res = await findAUser(ctx.params.id);

      if (res !== null) {
        ctx.body = {
          code: 0,
          message: "查询用户信息成功",
          result: res,
        };
      } else {
        return ctx.app.emit("error", invalidUserID, ctx);
      }
    } catch (error) {
      console.error(error);
    }
  }

  async update(ctx) {
    try {
      const res = await updateUser(ctx.params.id, ctx.request.body);

      if (res) {
        ctx.body = {
          code: 0,
          message: "用户信息修改成功",
          result: "",
        };
      } else {
        return ctx.app.emit("error", invalidUserID, ctx);
      }
    } catch (error) {
      console.error(error);
    }
  }
}

module.exports = new UserController();
